package com.memoryangelapplication;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.memoryangelapplication.AlertMessagePreviewAdapter.SoundManager;
import com.memoryangelapplication.AlertMessagePreviewAdapter.SoundManager1;
import com.memoryangelapplication.services.EventAlarm;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;

public class MemoryAngelPageListener extends SimpleOnPageChangeListener {

	private SQLiteDatabase mydb;
	private static final String DATABASE_NAME = "memoryangel.db";
	private String MEM_EVENT = "table_events";
	private static final String TAG = null;
	String DateSendAct, TimeAct, Tzone;
	long TimeStampValue;
	long nextReminderTimeStamp;
	int counter = 0;
	// Declare Variables
	Context context;
	String[] title;
	String[] description;
	String[] reminder_date;
	String[] event_count_flag;

	// Handling Variables
	String[] event_id; // Index(0)
	String[] event_alam_time; // Index(8)
	String[] event_url; // Index(11)
	String[] event_package; // Index(12)
	String[] event_ack_count; // Index(15)
	String[] eventReminderTime; // Index(16)
	String[] eventReminderNumber; // Index(17)
	String[] eventWaitTime; // Index(18)
	String[] eventNotifyType; // Index(19)

	// Calculate Variables
	int eventwaittimePeriod = 0;
	int wait_time = 0;
	int reminder_number = 0;
	int event_reminder_time = 0;
	int eventTTS = 0;
	int eventContPlay = 0;
	int eventSoundGap = 0;
	int recordCount = 0;
	String evtDes;
	String updateEventId;
	String eventURL;
	String eventPackage;
	int readIndex = 0;
	MediaPlayer player;
	ScheduledThreadPoolExecutor executor;
	ScheduledThreadPoolExecutor executor1;
	Handler handler, main_handelr;
	SoundManager soundManager;
	SoundManager1 soundManager1;
	TextToSpeech talker;
	EditText eventmainid;
	Runnable r1;
	LayoutInflater inflater;
	Activity activity;
	String CurrentEventID;

	public MemoryAngelPageListener(Activity activity, String[] title,
			String[] description, String[] reminder_date,
			String[] event_count_flag, String[] event_id,
			String[] event_alam_time, String[] event_url,
			String[] event_package, String[] event_ack_count,
			String[] eventReminderTime, String[] eventReminderNumber,
			String[] eventWaitTime, String[] eventNotifyType) {

		this.activity = activity;
		this.context = activity.getApplicationContext();
		this.title = title;
		this.description = description;
		this.reminder_date = reminder_date;
		this.event_count_flag = event_count_flag;

		this.event_id = event_id;
		this.event_alam_time = event_alam_time;
		this.event_url = event_url;
		this.event_package = event_package;
		this.event_ack_count = event_ack_count;
		this.eventReminderTime = eventReminderTime;
		this.eventReminderNumber = eventReminderNumber;
		this.eventWaitTime = eventWaitTime;
		this.eventNotifyType = eventNotifyType;
	}

	public void onPageSelected(int position) {
		Log.v("ALARM COMES HERE", "page selected " + description[position]
				+ "  >>>>>>>>>>>> " + position);
		readIndex = position;
		try {
			updateEventId = event_alam_time[position];
			String StrEventWaitTime = eventWaitTime[position];
			eventwaittimePeriod = Integer.parseInt(StrEventWaitTime);
			wait_time = eventwaittimePeriod * 1000;
			
			// ***********************************************
			// Time Zone Of the Current Phone
			Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
			Date currentLocalTime = calendar.getTime();
			DateFormat date = new SimpleDateFormat("Z");
			Tzone = date.format(currentLocalTime);
			Tzone = " " + Tzone;
			String currentTime = getAddDateTimeStringPreCheck();
			String[] CheckDayTime = currentTime.split(" ");
			DateSendAct = CheckDayTime[0];
			TimeAct = CheckDayTime[1];
			getNativeTimeStamp(DateSendAct, TimeAct, Tzone);
			// ***********************************************

			try {
				// Schedule Events Threads Handling Sounds and Display
				executor = new ScheduledThreadPoolExecutor(1);
				executor1 = new ScheduledThreadPoolExecutor(1);
				talker = new TextToSpeech(activity, (OnInitListener) activity);
				
				executor.shutdown();
				executor.shutdownNow();
				executor.remove(soundManager);

				executor1.shutdown();
				executor1.shutdownNow();
				executor1.remove(soundManager1);
				
				if (talker != null) {
					talker.stop();
					talker.shutdown();
				}
				player = new MediaPlayer();
				
				
				if(player.isLooping()){
					Log.v(">>>>>>>>>>>","isLooping");
					player.stop();
					player.reset();
					player.release();
				}
				else if(player.isPlaying()){
					Log.v("<<<<<<<<<<<","isPlaying");
					player.stop();
					player.reset();
					player.release();
				}


				executor = new ScheduledThreadPoolExecutor(1);
				executor1 = new ScheduledThreadPoolExecutor(1);
				talker = new TextToSpeech(activity, (OnInitListener) activity);
				player = new MediaPlayer();
				
				main_handelr = new Handler();

				new CountDownTimer(wait_time, 1000) {
					public void onTick(long millisUntilFinished) {
						// closeExcecutor();
						// Log.v("Timmer Started", "Timmer Started");
					}

					// Remove Alertfrom the screen
					// Set Next Alert
					// Update Backend
					public void onFinish() {
						executor.shutdown();
						executor.shutdownNow();
						executor.remove(soundManager);

						executor1.shutdown();
						executor1.shutdownNow();
						executor1.remove(soundManager1);
						eventDetailsUpdate();
						setNextReminder();
						activity.finish();
						player.stop();

					}
				}.start();
			} catch (Exception e) {

			}

			// How many times alert need to be display
			if (reminder_number == 0) {
				reminder_number = 3;
			}
			// Reminder Delay
			if (event_reminder_time == 0) {
				event_reminder_time = 60;
			}
			// Display Reminder
			if (wait_time == 0) {
				// if 0 then default will be 5
				wait_time = 45 * 1000;
			}
			eventTTS = 1;
			eventContPlay = 1;
			eventSoundGap = 1000;
			if (eventSoundGap == 0) {
				eventSoundGap = 5;
			}
		} catch (Exception e) {

		}
		soundManager = new SoundManager();
		executor.scheduleAtFixedRate(soundManager, 0, 3000, TimeUnit.MILLISECONDS);
	}

	// =========================================================================

	protected void eventDetailsUpdate() {
		// TODO Auto-generated method stub
		mydb = activity.openOrCreateDatabase(DATABASE_NAME,
				Context.MODE_PRIVATE, null);
		Cursor checkPreEventsAckCount = null;

		try {
			String query = "SELECT event_log_id,event_time_stamp,event_alam_time,event_ack_count,eventReminderTime,eventReminderNumber,eventWaitTime,eventTimeStamp FROM table_events Where event_alam_time = '"
					+ updateEventId + "'";
			checkPreEventsAckCount = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (checkPreEventsAckCount != null) {
			if (checkPreEventsAckCount.getCount() > 0) {
				while (checkPreEventsAckCount.moveToNext()) {
					ContentValues updateEvetsCount = new ContentValues();
					String updateID = checkPreEventsAckCount.getString(0);
					String event_alam_time = checkPreEventsAckCount
							.getString(2);
					long event_alam_timecount = Long.parseLong(event_alam_time);

					String updateCounter = checkPreEventsAckCount.getString(3);
					String eventReminderTime = checkPreEventsAckCount
							.getString(4);
					String eventReminderNumber = checkPreEventsAckCount
							.getString(5);
					String eventWaitTime = checkPreEventsAckCount.getString(6);
					String eventCurrentTimeStamp = checkPreEventsAckCount
							.getString(7);

					int eventReminderNumbercount = Integer
							.parseInt(eventReminderNumber);
					// Event Reminder Time = Time 1
					long eventReminderTimecount = Long
							.parseLong(eventReminderTime);
					long eventeventWaitTimecount = Long
							.parseLong(eventWaitTime);
					long eventeventCurrentTimeStamp = Long
							.parseLong(eventCurrentTimeStamp);

					long curCount = Long.parseLong(updateCounter);
					curCount = curCount + 1;

					long newEventCurrentTimeStamp = (eventReminderTimecount + eventeventWaitTimecount)
							* curCount;
					newEventCurrentTimeStamp = newEventCurrentTimeStamp
							+ TimeStampValue;
					String newEventCurrentTimeStampStr = String
							.valueOf(newEventCurrentTimeStamp);

					if (eventReminderNumbercount == curCount) {
						updateEvetsCount.put("event_status", "4");
						updateEvetsCount.put("event_ack_count", curCount);
						updateEvetsCount.put("event_active", "1");
						updateEvetsCount.put("event_alam_time",
								newEventCurrentTimeStampStr);
						mydb.update(MEM_EVENT, updateEvetsCount,
								"event_log_id ='" + updateID + "'", null);
					} else {
						nextReminderTimeStamp = newEventCurrentTimeStamp;
						newEventCurrentTimeStampStr = String
								.valueOf(nextReminderTimeStamp);
						updateEvetsCount.put("event_ack_count", curCount);
						updateEvetsCount.put("event_status", "9");
						updateEvetsCount.put("event_alam_time",
								newEventCurrentTimeStampStr);
						mydb.update(MEM_EVENT, updateEvetsCount,
								"event_log_id ='" + updateID + "'", null);
					}

				}
			}
		}
		checkPreEventsAckCount.close();
		mydb.close();

	}

	class SoundManager implements Runnable {

		/*int index;

		public SoundManager(int index) {
			this.index = index;
		}
*/
		int counter = 0;

		@Override
		public void run() {

			if ((counter % 2) == 0) {

				activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
				// our file here is in fact called "soundfile.mp3";

				player = MediaPlayer.create(activity, R.raw.alarm);

				// we start playing the file!
				player.start();

				player.setOnCompletionListener(new OnCompletionListener() {

					@Override
					public void onCompletion(MediaPlayer mp) {
						mp.stop();
						mp.release();

					}
				});

			} else if ((counter % 2) != 0) {
				String text = description[readIndex];
				talker.speak(text, TextToSpeech.QUEUE_FLUSH, null);
			}
			counter++;
		}

	}

	class SoundManager1 implements Runnable {

		@Override
		public void run() {

			activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
			// our file here is in fact called "soundfile.mp3";

			player = MediaPlayer.create(activity, R.raw.alarm);
			// we start playing the file!
			player.start();

			player.setOnCompletionListener(new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					mp.stop();
					mp.release();
				}
			});
		}

	}

	// ===========================================================

	protected void setNextReminder() {
		Bundle bundle = new Bundle();
		EventAlarm alarm1 = new EventAlarm(context, bundle, event_reminder_time);
	}

	// ===========================================================

	public long getNativeTimeStamp(String DateSend, String Time, String Tzone) {
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm zzzzz");
		Calendar c = Calendar.getInstance();
		Date d = null;

		try {
			d = ddMMMyyFormat
					.parse(DateSend.trim() + " " + Time.trim() + Tzone);

		} catch (ParseException e) {
			e.printStackTrace();
		}

		c.setTime(d);

		String date_to_string = ddMMMyyFormat
				.format(c.getTimeInMillis() / 1000);
		TimeStampValue = c.getTimeInMillis() / 1000;
		return c.getTimeInMillis() / 1000;
	}

	// ==========================================================

	private String getAddDateTimeStringPreCheck() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	/*		// Media Player handling events
	if (eventTTS == 1 && eventContPlay == 1) {
		//counter++;
		soundManager = new SoundManager();
		executor.scheduleAtFixedRate(soundManager, 0, 3000, TimeUnit.MILLISECONDS);
	} else if (eventTTS == 1 && eventContPlay == 0) {
		if (AlertMessagePreview.counter == 0) {
			AlertMessagePreview.counter++;
			activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
			// our file here is in fact called "soundfile.mp3";
			MediaPlayer player = MediaPlayer.create(activity , R.raw.alarm);
			// we start playing the file!
			player.start();
			player.setOnCompletionListener(new OnCompletionListener() {
				@Override
				public void onCompletion(MediaPlayer mp) {
					mp.stop();
					mp.release();
					Handler handler = new Handler();
					final Runnable r = new Runnable() {
						public void run() {
							String text = evtDes;
							talker.speak(text, TextToSpeech.QUEUE_FLUSH, null);
						}
					};
					handler.postDelayed(r, 3000);
				}
			});
		}

	} else if (eventTTS == 0 && eventContPlay == 1) {
		soundManager1 = new SoundManager1();
		executor1.scheduleAtFixedRate(soundManager1, 0, 3000, TimeUnit.MILLISECONDS);
	} else if (eventTTS == 0 && eventContPlay == 0) {
		if (counter == 0) {
			
			counter++;

			activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
			// our file here is in fact called "soundfile.mp3";

			MediaPlayer player = MediaPlayer.create(activity, R.raw.alarm);
			// we start playing the file!
			player.start();
			
			player.setOnCompletionListener(new OnCompletionListener() {
				@Override
				public void onCompletion(MediaPlayer mp) {
					mp.stop();
					mp.release();
				}
			});
		}
	}*/
}
